import React, { useState, useEffect, useRef } from 'react';
import App from 'app';

const ImageGrid = () => {
    // const imageUrls = Array.from(
    //     { length: 20 },
    //     (_, i) => `https://picsum.photos/200/300?random=${i + 1}`
    // );
    const { assetsURL } = App;

    const imageUrls = Array.from(
        { length: 40 },
        (_, i) => `${assetsURL}images/empty-pic/${i + 1}@2x.jpg`
    );

    const textList = [
        'Imagination',
        'Creativity',
        'Technology',
        'Curiosity',
        'Code',
        'Art',
        'Mathematics',
        'Intelligence',
        'Algorithms',
        'Aesthetics',
    ];

    const [gridImages, setGridImages] = useState([]);
    const [currentText, setCurrentText] = useState(textList[0]);
    const [nextText, setNextText] = useState(null);
    const textRef = useRef(null);

    // 初始化网格图片
    const initGrid = () => {
        const shuffled = [...imageUrls]
            .sort(() => 0.5 - Math.random())
            .slice(0, 9);
        setGridImages(shuffled);
    };

    // 替换随机图片
    const replaceRandomImages = () => {
        const randomN = Math.floor(Math.random() * 4) + 1;

        setGridImages((prev) => {
            const indices = [...Array(9).keys()]
                .sort(() => 0.5 - Math.random())
                .slice(0, randomN);

            let unusedImages = imageUrls.filter((url) => !prev.includes(url));

            if (unusedImages.length < randomN) {
                const usedButAvailable = prev.filter(
                    (_, i) => !indices.includes(i)
                );
                unusedImages = [
                    ...unusedImages,
                    ...usedButAvailable
                        .sort(() => 0.5 - Math.random())
                        .slice(0, randomN - unusedImages.length),
                ];
            }

            const replacements = unusedImages
                .sort(() => 0.5 - Math.random())
                .slice(0, randomN);

            const newImages = [...prev];
            indices.forEach((index, i) => {
                newImages[index] = replacements[i];
            });

            return newImages;
        });
    };

    const changeText = () => {
        // 随机选择下一个不同的文本
        const availableTexts = textList.filter((text) => text !== currentText);
        const randomIndex = Math.floor(Math.random() * availableTexts.length);

        // 更新nextText状态
        setNextText(availableTexts[randomIndex]);

        requestAnimationFrame(() => {
            // 检查 textRef.current 是否存在
            if (textRef.current) {
                const currentTextElement =
                    textRef.current.querySelector('.current-text');
                const nextTextElement =
                    textRef.current.querySelector('.next-text');

                if (currentTextElement && nextTextElement) {
                    // 添加switching类以触发动画
                    currentTextElement.style.transform = 'translateY(-100%)';
                    nextTextElement.style.transform = 'translateY(0%)';
                    nextTextElement.style.opacity = '1';

                    // 动画结束后更新currentText并移除switching类
                    setTimeout(() => {
                        setCurrentText(availableTexts[randomIndex]);

                        if (textRef.current) {
                            const current =
                                textRef.current.querySelector('.current-text');
                            const next =
                                textRef.current.querySelector('.next-text');

                            if (current && next) {
                                current.style.opacity = '0';
                                current.style.transform = 'translateY(0)';
                            }
                        }
                    }, 500); // 动画持续时间

                    setTimeout(() => {
                        if (textRef.current) {
                            const current =
                                textRef.current.querySelector('.current-text');
                            const next =
                                textRef.current.querySelector('.next-text');

                            if (current && next) {
                                current.style.opacity = '1';
                                next.style.opacity = '0';
                                next.style.transform = 'translateY(100%)';
                            }
                        }
                    }, 1200); // 动画持续时间
                }
            }
        });
    };

    useEffect(() => {
        initGrid();
        const imageInterval = setInterval(replaceRandomImages, 500);
        const textInterval = setInterval(changeText, 2000);

        return () => {
            clearInterval(imageInterval);
            clearInterval(textInterval);
        };
    }, [currentText, nextText]);

    return (
        <div className="img-grid-container">
            {gridImages.map((url, index) => (
                <div key={`${url}-${index}`} className="img-grid-item">
                    <img src={url} alt={`Grid ${index}`} />
                </div>
            ))}

            <div className="animation-text">
                <img
                    src="https://img.alicdn.com/imgextra/i3/O1CN01OjXVmz1WOpivsk8pl_!!6000000002779-2-tps-125-24.png"
                    alt=""
                    className="logo-img"
                />

                <div className="text-container" ref={textRef}>
                    <div className={`current-text`}>{currentText}</div>
                    <div className={`next-text`}>{nextText}</div>
                </div>

                <p>can take you to anywhere.</p>
            </div>
        </div>
    );
};

export default ImageGrid;
